package com.masu.knows.portal.controller;


import com.github.pagehelper.PageInfo;
import com.masu.knows.portal.dto.QuestionDTO;
import com.masu.knows.portal.model.Question;
import com.masu.knows.portal.service.IQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 沈传尚
 * @since 2021-12-07
 */
@RestController
@Slf4j
@RequestMapping("/v1/questions")
public class QuestionController {
    @Autowired
    private IQuestionService questionService;

    //@PathVariable可以用来映射URL中的占位符到目标方法的参数中
    @GetMapping("/{id}")
    public Question question(@PathVariable Integer id){
        return questionService.findQuestionById(id);
    }


    // 根据当前登录用户查询用户问题列表
    @GetMapping("/my")
    // 参数中使用注解获得当前登录的用户信息
    public PageInfo<Question> my(@AuthenticationPrincipal UserDetails user, Integer pageNum){
        if (Objects.isNull(pageNum)){
            pageNum=1;
        }
        return questionService.getMyQuestions(user.getUsername(),pageNum,8);
    }

    // 讲师首页表展示
    @GetMapping("/teacher")
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    public PageInfo<Question> teacher(@AuthenticationPrincipal UserDetails user, Integer pageNum){
        if (Objects.isNull(pageNum)){
            pageNum=1;
        }
        return questionService.getTeacherQuestions(user.getUsername(),pageNum,8);
    }



    @PostMapping("")
    public String createQuestion(@Validated QuestionDTO questionDTO, BindingResult result,@AuthenticationPrincipal UserDetails user){
        log.debug("接收到信息{}",questionDTO);
        if (result.hasErrors()){
            return Objects.requireNonNull(result.getFieldError()).getDefaultMessage();
        }
        try {
            questionService.saveQuestion(questionDTO,user.getUsername());
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @PostMapping(value = "/delete/{qid}")
    public String delete(@PathVariable("qid")Integer qid){
        try {
            questionService.deleteQuestion(qid);
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败";
        }
        return "删除成功";
    }

}
